import {ref} from 'vue'
import {defineStore} from 'pinia'
import {genDateTime} from "@/utils/getDateTime.js";
import {renameDuplicates} from "@/utils/dataHandler.js";


export const useUserProfile = defineStore(
    'userProfile',
    () => {
        // 预置用例
        const generalTestcase = {
            "key": "通用用例",
            "id": 1,
            "label": "通用用例",
            "createTime": "2024-10-08",
            "modifyTime": "2025-12-10",
            "author": "zzy",
            "remark": "xxx",
            "commandList": [],
            "readOnly": true,
        }

        // 初始串口配置标签[光学头,重构线,工程遥测,...]
        const initialTabList = [
            // 初始自带配置
            {
                label: "光学头",
                asLabel: "optical",
                serialConfig: {
                    port: "COM7",
                    baudrate: 1000000,
                    bytesize: 8,
                    parity: "odd",
                    stopbits: 1,
                    buffer_size: 1024 * 1024 * 10,
                    keep_reading: 'hardware'
                },
                closable: false,
                connected: false,
                appReader: null,
                appWriter: null,
                keepReading: true,
                telemetry: [
                    {
                        "dateTime": genDateTime(),
                        "sourceCode": "暂未收到遥测源码",
                        "byteLength": 0
                    }
                ],
                isAutoScroll: true,
                isAutoRead: true,
            },
            {
                label: "光学头重构",
                asLabel: "refactor",
                serialConfig: {
                    port: "COM7",
                    baudrate: 1000000,
                    bytesize: 8,
                    parity: "odd",
                    stopbits: 1,
                    buffer_size: 1024 * 1024 * 10,
                    keep_reading: 'hardware'
                },
                closable: false,
                connected: false,
                appReader: null,
                appWriter: null,
                keepReading: true,
                telemetry: [
                    {
                        "dateTime": genDateTime(),
                        "sourceCode": "暂未收到遥测源码",
                        "byteLength": 0
                    }
                ],
                isAutoScroll: true,
                isAutoRead: false
            },
            {
                label: "光学头工程数据",
                asLabel: "captureData",
                serialConfig: {
                    port: "COM7",
                    baudrate: 1000000,
                    bytesize: 8,
                    parity: "odd",
                    stopbits: 1,
                    buffer_size: 1024 * 1024 * 10,
                    keep_reading: 'hardware'
                },
                closable: false,
                connected: false,
                appReader: null,
                appWriter: null,
                keepReading: true,
                telemetry: [
                    {
                        "dateTime": genDateTime(),
                        "sourceCode": "暂未收到遥测源码",
                        "byteLength": 0
                    }
                ],
                isAutoScroll: false,
                isAutoRead: false
            },
        ]

        // 配置, 标签页,用例,流程,...
        const devProfile = {
            // 存储各个设备的配置
            tabList: JSON.parse(JSON.stringify(initialTabList)),
            // 存储测试用例
            testcases: [
                {
                    label: "测试用例(单击选中)",
                    key: "testcase",
                    children: [
                        generalTestcase,
                    ]
                }
            ],
            // 存储流程
            processes: [],
            // 当前打开的用例
            currentTestcase: generalTestcase,
            // 最后一次打开的用例
            lastTestcase: null,
            // 自定义遥测筛选项, 预置了几个
            filterList: [
                {
                    label: '重构',
                    value: '重构'
                },
                {
                    label: '开关',
                    value: '开关'
                },
                {
                    label: '温度',
                    value: '温度'
                },
                {
                    label: '指令跟随',
                    value: '指令跟随'
                }
            ]
        }

        // 设备列表
        const deviceList = ref([
            {
                deviceName: "光学头",
                alias: "optical",
                type: "warning",
                // 排除字段
                exclude_params: null,
                // 指令选项
                options: null
            },
            {deviceName: "蓝转台", type: "info", detail: {}},
            {deviceName: "CCD相机", type: "success", detail: {}}
        ])
        // 指令配置
        const commandConfig = reactive({
            "optical": null,
            "turntable": null,
            "camera": null,
        })
        // 遥测配置
        const telemetryConfig = reactive({
            optical: {
                // 遥测协议
                telemetry: null,
                // 格式化列表["uint8", "uint16",...]
                formatList: null
            },
            turntable: null,
            camera: null
        })
        // 当前使用版本信息
        const selectedVersion = ref({optical: {command: "v42", telemetry: "v43"}});  // 默认 v24
        /**
         * 更新配置的方法
         * {
         *     optical:{
         *         command: "v24",
         *         telemetry:"v29"
         *     }
         * }
         */
        const updateConfigs = async (obj) => {
            selectedVersion.value = obj
            try {
                const command = obj.optical.command;
                const telemetry = obj.optical.telemetry;

                // 使用 fetch 加载
                const commandRes = await fetch(`/deviceConfig/${command}/optical_instruction_${command}.json`);
                const commandModule = await commandRes.json();

                const telemetryRes = await fetch(`/deviceConfig/${telemetry}/optical_telemetry_${telemetry}.json`);
                const telemetryModule = await telemetryRes.json();
                // 指令配置更新
                const deviceIndex = deviceList.value.findIndex(item => item.alias === "optical")
                deviceList.value[deviceIndex] = {
                    ...deviceList.value[deviceIndex], // 保留原有属性
                    exclude_params: commandModule.exclude_params,
                    options: commandModule.instruction_set.map(item => ({
                        label: item.label,
                        value: item.params
                    }))
                };
                commandConfig.optical = commandModule

                telemetryConfig.optical = {
                    telemetry: renameDuplicates(telemetryModule.telemetry, "name"),
                    formatList: telemetryModule.telemetry.map(item => `${item.type}${item.bit_length}`)
                }

                // ...后续处理逻辑
            } catch (error) {
                console.error("加载失败:", error);
            }
        }

        // 启动时加载
        updateConfigs({
            optical: {
                command: "v42",
                telemetry: "v43"
            }
        }).then(() => console.log("配置加载成功")).catch(e => console.error(e));

        // 最新接收到的遥测记录
        const latestTelemetryData = ref({})
        const setLatestTelemetryData = (obj) => {
            latestTelemetryData.value = obj
        }

        // 配置对象
        const profile = ref(devProfile)

        const setUserProfile = (key, value) => {
            profile.value = {...profile.value, [key]: value};
        }
        // 增加子项
        const addTestcase = (testcaseItem) => {
            // 添加测试用例
            profile.value.testcases[0].children.push(testcaseItem);
        };

        // 删除子项
        const removeTestcase = (index) => {
            profile.value.testcases[0].children.splice(index, 1);
        };
        const openTestcase = (key) => {
            profile.value.currentTestcase = profile.value.testcases[0].children.find(tc => tc.key === key)
        }

        /**
         * 保存用例
         * @param testcaseItem 单个用例对象
         */
        const saveTestcase = (testcaseItem) => {
            const lastIndex = profile.value.testcases[0].children.findIndex(tc => tc.key === testcaseItem.key)
            if (lastIndex > -1) {
                profile.value.testcases[0].children[0][lastIndex] = testcaseItem;
            }
        }
        // 重置为默认配置
        const clearProfile = () => {
            profile.value = devProfile
        }


        return {
            profile,
            deviceList,
            setUserProfile,
            clearProfile,
            latestTelemetryData,
            setLatestTelemetryData,
            commandConfig,
            telemetryConfig,
            addTestcase,
            removeTestcase,
            saveTestcase,
            initialTabList,
            updateConfigs,
            selectedVersion,
            openTestcase
        }
    },
    {
        persist: [
            {
                storage: sessionStorage,
                pick: ['serialPortInstances']
            },
            {
                storage: localStorage,
                pick: ['latestTelemetryData', 'profile'],
            },
        ]
    }
)